import { createSlice, createAsyncThunk } from '@reduxjs/toolkit'

// 模拟用户数据
const mockUserData = {
  id: 'U001',
  username: 'StarYun',
  realName: '王*柯',
  registrationNo: '2015****10',
  avatar: '/api/avatar',
  phone: '138****8888',
  idCard: '110101199001011234',
  gender: '女',
  age: 28,
  emergencyContact: {
    name: '王妈妈',
    phone: '139****9999',
    relationship: '母亲'
  }
}

const mockFamilyMembers = [
  {
    id: 'F001',
    name: '王*柯',
    relationship: '本人',
    registrationNo: '2015****10',
    gender: '女',
    age: 28,
    phone: '138****8888'
  },
  {
    id: 'F002',
    name: '王妈妈',
    relationship: '母亲',
    registrationNo: '2015****11',
    gender: '女',
    age: 55,
    phone: '139****9999'
  }
]

// 异步thunk
export const fetchUserData = createAsyncThunk(
  'user/fetchUserData',
  async () => {
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 300))
    return mockUserData
  }
)

export const fetchFamilyMembers = createAsyncThunk(
  'user/fetchFamilyMembers',
  async () => {
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 300))
    return mockFamilyMembers
  }
)

export const updateUserProfile = createAsyncThunk(
  'user/updateUserProfile',
  async (userData) => {
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 500))
    return userData
  }
)

export const addFamilyMember = createAsyncThunk(
  'user/addFamilyMember',
  async (memberData) => {
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 500))
    return { ...memberData, id: `F${Date.now()}` }
  }
)

// 初始状态
const initialState = {
  userData: null,
  familyMembers: [],
  loading: false,
  error: null
}

// 创建slice
const userSlice = createSlice({
  name: 'user',
  initialState,
  reducers: {
    // 更新用户头像
    updateUserAvatar: (state, action) => {
      if (state.userData) {
        state.userData.avatar = action.payload
      }
    },
    // 更新用户基本信息
    updateUserBasicInfo: (state, action) => {
      if (state.userData) {
        state.userData = { ...state.userData, ...action.payload }
      }
    },
    // 移除家庭成员
    removeFamilyMember: (state, action) => {
      state.familyMembers = state.familyMembers.filter(
        member => member.id !== action.payload
      )
    },
    // 更新家庭成员信息
    updateFamilyMember: (state, action) => {
      const { id, ...updateData } = action.payload
      const memberIndex = state.familyMembers.findIndex(member => member.id === id)
      if (memberIndex !== -1) {
        state.familyMembers[memberIndex] = { ...state.familyMembers[memberIndex], ...updateData }
      }
    },
    // 清除错误
    clearError: (state) => {
      state.error = null
    }
  },
  extraReducers: (builder) => {
    builder
      // 获取用户数据
      .addCase(fetchUserData.pending, (state) => {
        state.loading = true
        state.error = null
      })
      .addCase(fetchUserData.fulfilled, (state, action) => {
        state.loading = false
        state.userData = action.payload
      })
      .addCase(fetchUserData.rejected, (state, action) => {
        state.loading = false
        state.error = action.error.message
      })
      // 获取家庭成员
      .addCase(fetchFamilyMembers.pending, (state) => {
        state.loading = true
        state.error = null
      })
      .addCase(fetchFamilyMembers.fulfilled, (state, action) => {
        state.loading = false
        state.familyMembers = action.payload
      })
      .addCase(fetchFamilyMembers.rejected, (state, action) => {
        state.loading = false
        state.error = action.error.message
      })
      // 更新用户资料
      .addCase(updateUserProfile.fulfilled, (state, action) => {
        state.userData = { ...state.userData, ...action.payload }
      })
      // 添加家庭成员
      .addCase(addFamilyMember.fulfilled, (state, action) => {
        state.familyMembers.push(action.payload)
      })
  }
})

// 导出actions
export const {
  updateUserAvatar,
  updateUserBasicInfo,
  removeFamilyMember,
  updateFamilyMember,
  clearError
} = userSlice.actions

// 导出selectors
export const selectUserData = (state) => state.user.userData
export const selectFamilyMembers = (state) => state.user.familyMembers
export const selectUserLoading = (state) => state.user.loading
export const selectUserError = (state) => state.user.error

// 导出reducer
export default userSlice.reducer
